import AsyncStorage from '@react-native-community/async-storage'

export default class DataStore{
    //检验时间(设定为4小时内有效)
    static checkTimestampvalid(timestamp){
        let currentDate = new Date()
        let targetData = new Date()
        targetData.setTime(timestamp)
        if (currentDate.getMonth() !== targetData.getMonth()) return false
        if (currentDate.getDate() !== targetData.getDate()) return false
        if (currentDate.getHours() - targetData.getHours() > 4) return false
        return true
    }

    //获取数据 - 总流程
    fetchData(url){
        return new Promise((resolve, reject) => {
            //获取本地数据
            this.fetchLocalData(url)
            .then(wrapdata => {
                //检查有效期
                if (wrapdata && DataStore.checkTimestampvalid(wrapdata.timestamp)) {
                    resolve(wrapdata)
                }else{
                    //获取网络数据
                    this.fetchNetData(url)
                    .then(data => {
                        resolve(this._wrapData(data))
                    })
                    .catch(e => {
                        reject(e)
                    })
                }
            })
            .catch(error => {
                this.fetchNetData(url)
                .then(data => {
                    resolve(this._wrapData(data))
                })
                .catch(e => {
                    reject(e)
                })
            })
        })
    }

    //存储数据
    saveData(key, value, callback){
        if (!key || !value) return
        AsyncStorage.setItem(key, JSON.stringify(this._wrapData(value)), callback)
    }

    //给数据加时间戳
    _wrapData(value) {
        return {
            data: value,
            timestamp: new Date().getTime() //最好用服务器时间
        }
    }

    //获取本地数据
    fetchLocalData(key){
        return new Promise((resolve, reject) => {
            AsyncStorage.getItem(key, (err, result) => {
                if (!err) {
                    resolve(JSON.parse(result))
                }else{
                    reject(err)
                    console.log(err)
                }
            })
        })
    }

    //获取网络数据
    fetchNetData(url){
        return new Promise((resolve, reject) => {
            fetch(url)
            .then(response => {
                if (response.ok) {
                    return response.json()
                }
                throw new Error("请求异常")
            })
            .then(responseData => {
                this.saveData(url, responseData) //把请求路径当作key
                resolve(responseData)
            })
            .catch(err => {
                reject(err)
                console.log(err)
            })
        })
    }
}